<template>
  <div>
    <div class="my-tree">
      <el-tree
        ref="treeRef"
        show-checkbox
        check-strictly
        :data="list"
        node-key="id"
        :props="{label:'name'}"
        @node-click="handleNodeClick"
      />
    </div>
    <div class="permission-btns">
      <el-button type="primary" round @click="onSubmit">确定</el-button>
      <el-button round @click="cancel">取消</el-button>
    </div>

  </div>
</template>
<script>
import { getAllPermissionRequest } from '@/api/permission'
import { assignPermissionRequest, getRolePermByIdRequest } from '@/api/setting'
// 导入将平铺数据转为树形结构的方法
import { transformListToTree2 } from '@/utils'
export default {
  name: '',
  props: {
    currntId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.getPermission()
    this.getRolePermById()
  },
  methods: {
    async getPermission() {
      try {
        const res = await getAllPermissionRequest()
        console.log('getAllPermissionRequest: ', res)
        if (res.success) {
          this.$message.success(res.message)
          this.list = transformListToTree2(res.data, '0')
          console.log(this.list)
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        console.log('getAllPermissionRequest: ', err)
      }
    },
    cancel() {
      this.$emit('close')
    },
    handleNodeClick(data) {
      console.log(data)
    },
    async assignPermission() {
      console.log(this.currntId)
      try {
        const res = await assignPermissionRequest({
          id: this.currntId,
          permIds: this.$refs.treeRef.getCheckedKeys()
        })
        console.log('assignPermissionRequest: ', res)
        if (res.success) {
          this.$message.success(res.message)
          this.getPermission()
          this.cancel()
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        console.log('assignPermissionRequest: ', err)
      }
    },
    async getRolePermById() {
      try {
        const res = await getRolePermByIdRequest(this.currntId)
        console.log('getRolePermByIdRequest: ', res)
        if (res.success) {
          this.$message.success(res.message)
          this.$refs.treeRef.setCheckedKeys(res.data?.permIds || [])
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        console.log('getRolePermByIdRequest: ', err)
      }
    },
    onSubmit() {
      console.log(this.$refs.treeRef.getCheckedNodes())
      console.log(this.$refs.treeRef.getCheckedKeys())
      this.assignPermission()
    }
  }

}
</script>
